package com.superman.service.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class HandleThread extends Thread {
    private Socket socket;//让线程持有 socket,一个 socket 可以对应多个线程

    public HandleThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //获取客户端的请求流
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String request = bufferedReader.readLine();
            String response = new AllService().getResponse(request);

            //将响应写入到socket
            printWriter = new PrintWriter(socket.getOutputStream(), true);
            printWriter.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
                printWriter.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}